package httpclient

import (
	"bufio"
	"bytes"
	"encoding/json"
	"gitee.com/guolianyu/cpkg/mail/v2"
	"go.uber.org/zap"
)

/*
	设置失败时告警
*/

// AlarmVerify Verify parse the body and verify that it is correct
// 验证解析正文并验证其正确性
type AlarmVerify func(body []byte) (shouldAlarm bool)

type AlarmObject interface {
	Send(subject, body string) error
}

type AlarmEmail struct{}

func (a *AlarmEmail) Send(subject, body string) error {
	options := &mail.Options{
		MailHost: "smtp.163.com",
		MailPort: 465,
		MailUser: "xx@163.com",
		MailPass: "",
		MailTo:   "",
		Subject:  subject,
		Body:     body,
	}
	return mail.Send(options)
}

// 需要去实现 AlarmVerify 方法，比如这样：
func alarmVerify(body []byte) (shouldalarm bool) {
	if len(body) == 0 {
		return true
	}

	type Response struct {
		Code int `json:"code"`
	}
	resp := new(Response)
	if err := json.Unmarshal(body, resp); err != nil {
		return true
	}

	// 当第三方接口返回的 code 不等于约定的成功值（1）时，就要进行告警
	return resp.Code != 1
}

func onFailedAlarm(title string, raw []byte, logger *zap.Logger, alarmObject AlarmObject) {
	buf := bytes.NewBuffer(nil)

	scanner := bufio.NewScanner(bytes.NewReader(raw))

	for scanner.Scan() {
		buf.WriteString(scanner.Text())
		buf.WriteString(" <br/>")
	}

	if err := alarmObject.Send(title, buf.String()); err != nil && logger != nil {
		logger.Error("calls failed alarm err", zap.Error(err))
	}

}
